import { domain } from '../theme/theme';
var server = require('./server');
var env = wx.getAccountInfoSync().miniProgram.envVersion || "release";
var basePath, storePath, gamePath, trackPath, storePathBook, basePathBook, orderAgainFlag = false, isLogining = false, isCanPay = true

if (env == 'develop' || env == 'trial') {
    //basePath = `http://base-yaf.sg.com/api/`; // 测试环境
    basePath = `http://ljhtest.roi-cloud.com/api/`
} else {
    basePath = `http://ljhtest.roi-cloud.com/api/`; // 测试环境
}

module.exports = {
  basePath,
  storePath,
  gamePath,
  trackPath,
  storePathBook,
  basePathBook,
  gdKey: '',
  serverTel: '',

  showFail: function (msg) {
    wx.showToast({
      image: '/imgs/icon/fail.png',
      title: msg
    })
  },

  showLoading: function (title = '加载中...') {
    wx.showLoading({
      title: title,
      mask: true
    });
  },

  hideLoading: function () {
    wx.hideLoading()
  },

  showToast: function (mesg, duration = 1500) {
    wx.showToast({
      title: mesg,
      icon: 'none',
      duration
    })
  },

  showErrorToast: function (mesg, duration = 1500) {
    if (mesg == undefined) {
      this.showToast("数据出错啦T_T，请稍候再试 [-3]");
    }
    if (mesg != "") {
      wx.showToast({
        title: mesg,
        icon: 'none',
        duration
      })
    }
  },

  // 处理页面打开达到十个无法再打开问题
  navigateTo({ url }) {
    if (getCurrentPages().length >= 10) {
      wx.redirectTo({
        url: url,
        fail: res => {
          wx.switchTab({ url })
        },
      })
    } else {
      wx.navigateTo({
        url: url,
        fail: res => {
          wx.switchTab({ url })
        },
      })
    }
  },

  throttle(_this, _arguments, func, wait) {
    let timeout;
    return function () {
      if (!timeout) {
        timeout = setTimeout(() => {
          timeout = null;
          func.apply(_this, _arguments)
        }, wait)
      }
    }
  },

  // 获取当前页面
  getCurrentPage() {
    const pages = getCurrentPages();
    return pages[pages.length - 1];
  },

  // 版本号比较
  compareVersion(v1, v2) {
    v1 = v1.split('.')
    v2 = v2.split('.')
    const len = Math.max(v1.length, v2.length)

    while (v1.length < len) {
      v1.push('0')
    }
    while (v2.length < len) {
      v2.push('0')
    }

    for (let i = 0; i < len; i++) {
      const num1 = parseInt(v1[i])
      const num2 = parseInt(v2[i])

      if (num1 > num2) {
        return 1
      } else if (num1 < num2) {
        return -1
      }
    }

    return 0
  },


  // 校验登录
  checkLogin(app = getApp()) {
    return new Promise((resolve, reject) => {
      if (app.globalData.isLogin || app.globalData.isLogout || isLogining || !app.globalData.isAgreePrivacy) {
        resolve()
        return
      }
      wx.login({
        success: resp => {
          wx.getUserInfo({
            success: res => {
              isLogining = true
              server.login(this.basePath + 'miniprogram/login/', {
                "js_code": resp.code,
                "encryptedData": res.encryptedData,
                "iv": res.iv,
                "userinfo": res.userInfo,
                "longitude": app.globalData.locateLongitude,
                "latitude": app.globalData.locateLatitude,
                "province": app.globalData.locateProvince,
                "city": app.globalData.locateCity instanceof Array ? app.globalData.locateProvince : app.globalData.locateCity,
              }, res => {
                const { errno, errmsg, data } = res.data
                if (errno == "0") {
                  app.globalData.isLogin = true
                  wx.setStorageSync('sso', data.sso)
                  wx.setStorageSync('userInfo', data)
                } else {
                  this.showErrorToast(errmsg)
                }
                isLogining = false
                resolve(res.data)
              })
            },
            fail: res => {
              console.log('getUserInfo faillllll', res);
              isLogining = false
              track.specificType('getUserInfoFail')
              // 隐私授权同意后再次登录并回调
              // if (app.globalData.isAgreePrivacy && !app.globalData.isLogin && res.errno != '112') {
              //   this.checkLogin(app).then(resp => {
              //     resolve(res)
              //   })
              // } else {
              //   reject(res)
              // }
              reject(res)
            }
          })
        }
      })
    })
  },


  



  // 判断当前页是否为tab页
  judgeTabPage() {
    const tabPages = ['pages/index/index', 'pages/shop/productsListIndex', 'pages/memberPay/index', 'pages/cart/cartIndex', 'pages/user_center/index']
    let pages = getCurrentPages()
    let route = pages[pages.length - 1].route
    return tabPages.includes(route)
  },

 


  // 上传图片/视频
  chooseMedia(that, images, maxNum = 9, imgSize, videoSize) {
    if (images.length >= maxNum) {
      this.showErrorToast(`图片/视频最多只能上传${maxNum}个哦~`)
      return
    }
 
    wx.chooseMedia({
      count: maxNum - images.length,
      mediaType: ['mix'],
      sourceType: ['album', 'camera'],
      sizeType: ['compressed'],
      maxDuration: 30,
      camera: 'back',
      success: res => {
        const { tempFiles } = res
        for (let i = 0; i < tempFiles.length; i++) {
          const { tempFilePath, size, fileType } = tempFiles[i]
          if (tempFilePath) {
            const type = tempFilePath.split('.')[1]
            if (['png', 'jpg', 'jpeg', 'mpeg', 'avi', 'mov', 'mp4', 'm4v', '3gp', 'm3u8'].indexOf(type) == -1) {
              this.showToast(`暂不支持上传${type}类型文件`)
            } else if (fileType == 'image' && size > (1048576 * imgSize)) {
              this.showToast(`${tempFiles.length > 1 ? '部分' : ''}图片大小超出限制~`)
            } else if (size > (1048576 * videoSize)) {
              this.showToast(`${tempFiles.length > 1 ? '部分' : ''}视频大小超出限制~`)
            } else {
              images.push({
                url: tempFilePath,
                type: fileType
              })
            }
          }
        }
        that.setData({ images })
      }
    })
  },
// 上传付款图片/视频
choosePayMedia(that, pay_images, maxNum = 9, imgSize, videoSize) {
  if (pay_images.length >= maxNum) {
    this.showErrorToast(`图片/视频最多只能上传${maxNum}个哦~`)
    return
  }

  wx.chooseMedia({
    count: maxNum - pay_images.length,
    mediaType: ['mix'],
    sourceType: ['album', 'camera'],
    sizeType: ['compressed'],
    maxDuration: 30,
    camera: 'back',
    success: res => {
      const { tempFiles } = res
      for (let i = 0; i < tempFiles.length; i++) {
        const { tempFilePath, size, fileType } = tempFiles[i]
        if (tempFilePath) {
          const type = tempFilePath.split('.')[1]
          if (['png', 'jpg', 'jpeg', 'mpeg', 'avi', 'mov', 'mp4', 'm4v', '3gp', 'm3u8'].indexOf(type) == -1) {
            this.showToast(`暂不支持上传${type}类型文件`)
          } else if (fileType == 'image' && size > (1048576 * imgSize)) {
            this.showToast(`${tempFiles.length > 1 ? '部分' : ''}图片大小超出限制~`)
          } else if (size > (1048576 * videoSize)) {
            this.showToast(`${tempFiles.length > 1 ? '部分' : ''}视频大小超出限制~`)
          } else {
            pay_images.push({
              url: tempFilePath,
              type: fileType
            })
          }
        }
      }
      that.setData({ pay_images })
    }
  })
},
  // 图片视频预览
  previewMedia(images, current) {
    // 低版本兼容处理
    if (this.compareVersion(getApp().globalData.sdkversion, '2.15.0') < 0) {
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
      })
      return
    }
    wx.previewMedia({
      current,
      url: images[current].url,
      sources: images,
    });
  },
}
